<template>
  <el-card>
    <el-form :inline="true" :model="formInline" style="display: flex">
      <el-form-item>
        <el-input v-model="formInline.deviceTypeName" placeholder="设备类型名称" />
      </el-form-item>
      <el-form-item style="width: 100px">
        <el-select v-model="formInline.status" clearable placeholder="状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="flex: 1">
        <el-date-picker
            v-model="formInline.createTime"
            type="daterange"
            range-separator="到"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchDeviceType">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="showAddModal">添加设备类型</el-button>
    <el-button type="primary" @click="showUploadModal">数据导入</el-button>
    <el-button type="primary" @click="exportData">数据导出</el-button>
    <el-popconfirm title="确认删除?" @confirm="batchDeleteDeviceType">
      <template #reference>
        <el-button type="danger">批量删除</el-button>
      </template>
    </el-popconfirm>
    <el-table :data="deviceTypes" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="deviceTypeName" label="设备类型名称" align="center"></el-table-column>
      <el-table-column prop="series" label="归属系列" align="center"></el-table-column>
      <el-table-column prop="currentOutput" label="电流输出" align="center"></el-table-column>
      <el-table-column prop="portCount" label="设备端口数" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="{ row }">
          <el-radio-group v-model="row.status" is-button size="small" @change="updateDeviceTypeStatus(row)">
            <el-radio-button :label="i.label" :value="i.value" v-for="i in options" />
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showEditModal(row)">编辑</el-button>
          <el-popconfirm title="确认删除?" @confirm="deleteDeviceType(row.id)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100, 1000, 5000]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 添加设备类型模态框 -->
  <el-dialog v-model="addDialogVisible" title="添加设备类型">
    <el-form ref="addFormRef" :model="addFormData" label-width="120px" :rules="rules">
      <el-form-item label="设备类型名称" prop="deviceTypeName">
        <el-input v-model="addFormData.deviceTypeName"></el-input>
      </el-form-item>
      <el-form-item label="归属系列" prop="series">
        <el-input v-model="addFormData.series"></el-input>
      </el-form-item>
      <el-form-item label="电流输出" prop="currentOutput">
        <el-input v-model.number="addFormData.currentOutput"></el-input>
      </el-form-item>
      <el-form-item label="设备端口数" prop="portCount">
        <el-input v-model.number="addFormData.portCount"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDeviceType(addFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑设备类型模态框 -->
  <el-dialog v-model="editDialogVisible" title="编辑设备类型">
    <el-form ref="editFormRef" :model="editFormData" label-width="120px" :rules="rules">
      <el-form-item label="设备类型名称" prop="deviceTypeName">
        <el-input v-model="editFormData.deviceTypeName" disabled></el-input>
      </el-form-item>
      <el-form-item label="归属系列" prop="series">
        <el-input v-model="editFormData.series"></el-input>
      </el-form-item>
      <el-form-item label="电流输出" prop="currentOutput">
        <el-input v-model.number="editFormData.currentOutput"></el-input>
      </el-form-item>
      <el-form-item label="设备端口数" prop="portCount">
        <el-input v-model.number="editFormData.portCount"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="editFormData.status" is-button>
          <el-radio-button :label="i.label" :value="i.value" v-for="i in options" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelUpdateDeviceType()">取消</el-button>
        <el-button type="primary" @click="updateDeviceType(editFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 导入数据 -->
  <el-dialog v-model="uploadDialogVisible" title="导入数据">
    <el-upload class="upload-demo" drag :action="uploadURL" multiple :on-success="handleUploadSuccess">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到此处或者点击上传</div>
    </el-upload>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { fetchDeviceTypePage, postDeviceType, putDeviceType, delDeviceType, batchDelDeviceType, exportDeviceTypeData, fetchDeviceTypeById } from "@/api/DeviceTypeApi.ts";
import type { ElMessage, UploadProps, FormInstance, FormRules } from 'element-plus';
import { UploadFilled } from "@element-plus/icons-vue";
import {delUser} from "@/api/UserApi.ts";

interface DeviceType {
  id: number;
  deviceTypeName: string;
  series: string;
  currentOutput: number;
  portCount: number;
  createTime: string;
  updateTime: string;
  status: string;
}

const deviceTypes: DeviceType[] = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const addFormData: DeviceType = reactive({
  id: null,
  deviceTypeName: '',
  series: '',
  currentOutput: 0,
  portCount: 0,
  createTime: '',
  updateTime: '',
  status: ''
});
let editFormData: DeviceType = reactive({
  id: null,
  deviceTypeName: '',
  series: '',
  currentOutput: 0,
  portCount: 0,
  createTime: '',
  updateTime: '',
  status: ''
});
const multipleSelection = ref<DeviceType[]>([]);
const uploadDialogVisible = ref(false);
const uploadURL = ref(import.meta.env.VITE_APP_BASE_FILE_API);

const addFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  deviceTypeName: [
    { required: true, message: '设备类型名称不能为空', trigger: 'blur' },
  ],
  series: [
    { required: true, message: '归属系列不能为空', trigger: 'blur' },
  ],
  currentOutput: [
    { required: true, message: '电流输出不能为空', trigger: 'blur' },
  ],
  portCount: [
    { required: true, message: '设备端口数不能为空', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ]
});

const formInline: DeviceType = reactive({});

const options = ref([
  { value: '1', label: '正常' },
  { value: '0', label: '禁用' }
]);

const fetchDeviceType = async () => {
  const response = await fetchDeviceTypePage(currentPage.value, pageSize.value, {});
  deviceTypes.value = response.data.records;
  total.value = response.data.total;
};

const addDeviceType = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      return;
    }
    await postDeviceType(addFormData);
    addDialogVisible.value = false;
    await fetchDeviceType();
  });
};

const cancelUpdateDeviceType = () => {
  editDialogVisible.value = false;
  fetchDeviceType();
};

const updateDeviceType = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      return;
    }
    await putDeviceType(editFormData);
    editDialogVisible.value = false;
    await fetchDeviceType();
  });
};

const updateDeviceTypeStatus = async (deviceType: DeviceType) => {
  await putDeviceType(deviceType);
  editDialogVisible.value = false;
  await fetchDeviceType();
};

const deleteDeviceType = async (id: number) => {
  await delDeviceType(id);
  await fetchDeviceType();
};

const showAddModal = () => {
  addFormData.id = null;
  addFormData.deviceTypeName = '';
  addFormData.series = '';
  addFormData.currentOutput = 0;
  addFormData.portCount = 0;
  addFormData.createTime = '';
  addFormData.updateTime = '';
  addFormData.status = '';
  addDialogVisible.value = true;
};

const showEditModal = async (row: any) => {
  editFormData = { ...row };
  editFormRef.value?.clearValidate();
  editDialogVisible.value = true;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchDeviceType();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchDeviceType();
};

const handleSelectionChange = (val: DeviceType[]) => {
  multipleSelection.value = val;
};

const batchDeleteDeviceType = async () => {
  const ids: number[] = multipleSelection.value.map((deviceType: DeviceType) => deviceType.id);
  if (ids.length === 0) {
    return ElMessage.error("请先选中！");
  }
  await batchDelDeviceType(ids);
  await fetchDeviceType();
};

const showUploadModal = () => {
  uploadDialogVisible.value = true;
};

const handleUploadSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: any) => {
  ElMessage.success("导入成功");
  uploadDialogVisible.value = false;
  fetchDeviceType();
};

const exportData = async () => {
  const res = await exportDeviceTypeData();
  const blob = new Blob([res.data]);
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute('download', dayjs().format('YYYY-MM-DD HH:mm:ss') + ".csv");
  document.body.appendChild(link);
  link.click();
};

const searchDeviceType = async () => {
  let createTime = formInline.createTime;
  if (formInline.createTime) {
    formInline.createTime = dayjs(formInline.createTime[0]).format('YYYY-MM-DD HH:mm:ss') + ',' + dayjs(formInline.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
  }
  const response = await fetchDeviceTypePage(currentPage.value, pageSize.value, formInline);
  deviceTypes.value = response.data.records;
  total.value = response.data.total;
  formInline.createTime = createTime;
};

fetchDeviceType();
</script>

<style scoped>
.el-card {
  margin-top: 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 #ffffff;
  outline: 0;
}
</style>
